package com.cn.wanxi.util;

import java.sql.*;
import java.util.List;

/**
 * 连接数据库的代码封装
 * 手写步骤
 * 1.注册驱动
 * 2.得到连接
 * 3.编译sql语句
 * 4.执行sql语句
 * 5.返回结果集
 */
public class JDBC {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到连接的目的，就是别人要来调用我
     */
    private static Connection getConnnection() {
        try {
//            ?charSet=UTF-8&serviceErea=SHANGHAI
            String url = "jdbc:mysql://121.199.55.96:3306/canyin04";
            String user = "canyin04";
            String password = "123456";
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ResultSet query(String sql) {
//        String sql = "select * from  user";
        try {

            PreparedStatement preparedStatement = getConnnection().prepareStatement(sql);
            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int update(String sql) {
//        String sql = "select * from  user";
        try {
            PreparedStatement preparedStatement = getConnnection().prepareStatement(sql);
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static int updatea(String sql, List<Object> list) {
//        String sql = "select * from  user";
        try {
//            PreparedStatement和statement的区别？
            PreparedStatement preparedStatement = getConnnection().prepareStatement(sql);
//            for循环就是将值填入占位符？里面
            for (int i = 0; i < list.size(); i++) {
//                就是对sql语句？里面进行赋值
                preparedStatement.setObject(i + 1, list.get(i));
            }
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
//    public static void main(String[] args) {
//        System.out.println(new JDBC().query());
//    }
}
